﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Lastfm.Services;

namespace MediaArtAggregator.Core.SearchProvider {
	public class LastFMSearchSource : ApiBasedSearchSource {
		private const string API_KEY = "97bd965029459a2cc844e116296c3867";
		private const string API_SECRET = "9e1ed1a01b11be51aa745da73c2c24c9";

		public override void Search ( string search, MediaArtAggregator.Core.Configuration.Settings settings, MediaArtAggregator.Core.Configuration.SearchType searchType ) {
			this.OnSearchInitialize ( EventArgs.Empty );

			Lastfm.Services.Session session = new Lastfm.Services.Session ( API_KEY, API_SECRET );
			AlbumSearch albums = new AlbumSearch ( search, session );
			albums.SpecifyItemsPerPage ( 30 );
			foreach ( Album album in albums.GetPage ( 1 ) ) {
				string url = album.GetImageURL ( AlbumImageSize.ExtraLarge );
				if ( string.IsNullOrEmpty ( url ) ) {
					url = album.GetImageURL ( AlbumImageSize.Large );
				}

				if ( string.IsNullOrEmpty ( url ) ) {
					url = album.GetImageURL ( AlbumImageSize.Medium );
				}

				if ( string.IsNullOrEmpty ( url ) ) {
					url = album.GetImageURL ( AlbumImageSize.Small );
				}

				if ( !string.IsNullOrEmpty ( url ) ) {
					this.Results.Add ( new Uri ( url ) );
				}
			}

			this.OnSearchComplete ( EventArgs.Empty );
		}

		public override string ToString ( ) {
			return "last.fm";
		}
	}
}
